package Day019_Junit单元测试_NIO.demo5_ServerSocketChannel和SocketChannel;

import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author zhangyan
 * @date 2020/5/12 15:14
 */
public class Test2_Server {
    public static void main(String[] args) throws Exception{
        //ServerSocketChannel类用于连接的服务器端，它相当于：ServerSocket

        //创建ServerSocketChannel
        //调用ServerSocketChannel的静态方法open()：打开一个通道
        ServerSocketChannel ssc = ServerSocketChannel.open(); //打开通道

        //调用ServerSocketChannel的实例方法bind(SocketAddress add)：绑定本机监听端口，准备接受连接
        ssc.bind(new InetSocketAddress(8888));

        //设置非阻塞
        //false表示非阻塞 true表示阻塞
        ssc.configureBlocking(false);

        //调用ServerSocketChannel的实例方法accept()：返回SocketChannel对象,等待连接
        //SocketChannel sc = ssc.accept(); // 非阻塞方法

        while (true){
            SocketChannel sc = ssc.accept();
            // 如果没有客户端连接成功,就返回null,如果连接成功,就不是null
            if (sc != null){
                System.out.println("连接成功,正在处理...");
                break;
            } else {
                System.out.println("没人连接.玩会游戏...");
                Thread.sleep(5000);
            }
        }

    }
}
